package com.ruben.leetCode;/**
 * @ClassName: RemoveNthFromEndSolution
 * @Date: 2020/10/18 0018 00:49
 * @Description:
 */

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * @ClassName: RemoveNthFromEndSolution
 * @Description: 我还没有写描述
 * @Date: 2020/10/18 0018 0:49
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class RemoveNthFromEndSolution {
    /**
     * @MethodName: getListNodeLength
     * @Description: 遍历链表，获取长度
     * @Date: 2020/10/18 0018 22:13
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [head]
     * @returnValue: int
     */
    public static int getListNodeLength(ListNode head) {
        int count = 0;
        while (head != null) {
            head = head.next;
            count++;
        }
        return count;
    }

    /**
     * 给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode listNode = new ListNode(0, head);
        // 获取长度后再次遍历到长度-n
        int length = getListNodeLength(head);
        // 然后把链表赋值
        ListNode now = listNode;
        // 然后找到要删除的节点
        for (int i = 0; i < length - n; i++) {
            now = now.next;
        }
        // 找到后开始删除，把下个节点的next赋值给当前节点的next就可以完成删除
        now.next = now.next.next;
        return listNode.next;
    }

    /**
     * @MethodName: 自定义一个链表
     * @Description: 我还没有写描述
     * @Date: 2020/10/18 0018 22:02
     * *
     * @author: <achao1441470436@gmail.com>
     * @param:
     * @returnValue:
     */
    public static class ListNode {
        /**
         * 值
         */
        int val;
        /**
         * 末尾存放下一个节点
         */
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
